/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.DonHang;
import util.HibernateUtil;

/**
 *
 * @author KhanhNhac
 */
public class DonHangDAO {
    private static List ds;
     public static DonHang layThongTinDonHang(int maDonHang) {
        DonHang h = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            h = (DonHang) session.get(DonHang.class, maDonHang);
        } catch (HibernateException ex) {
            //Log the exception
            System.err.println(ex);
        } finally {
            session.close();
        }
        return h;
    }
    public static int sinhMaDonHang(int kh) {
        int maDonHang;
        SimpleDateFormat sdf= new SimpleDateFormat("HHmmssSSSddMMyyyy");
        Date d = new Date();
        String str = sdf.format(d);
        
        maDonHang = kh + d.getHours()+d.getMinutes();
        return maDonHang;
    }
    public static boolean themDonHang(DonHang h) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        if (DonHangDAO.layThongTinDonHang(h.getMaDonHang()) != null) {
            return false;
        }
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.save(h);
            transaction.commit();
        } catch (HibernateException ex) {
            //Log the exception
            transaction.rollback();
            System.err.println(ex);
        } finally {
            session.close();

        }
        return true;
    }
    public static List<DonHang> layDonHangTheoMaKH(int mKH){
        Session session=HibernateUtil.getSessionFactory().openSession();
        List<DonHang> dh;
        String hql="from DonHang s where s.khachHang.maKhachHang =:maKH";
        Query query=session.createQuery(hql);
        query.setInteger("maKH", mKH);
        dh=query.list();
        return dh;
    }
}
